<template>
  <div class="blog-code">
    <div class="blog-code__title-container">
      <div class="blog-code__title">
        <span>{{ language }}</span>
      </div>

      <div class="blog-code__controls">
        <el-popover placement="top"
                    trigger="manual"
                    v-model:visible="copied_popover">
          <p>已复制！</p>
          <template #reference>
            <button v-show="!fold" class="btn-copy" name="copy" type="button" @click="copy">
              <span class="material-icons">content_copy</span>
              <span>复制</span>
            </button>
          </template>

        </el-popover>
        <button class="btn-expand" type="button" @click="fold = !fold">
          <span :class="fold?'btn-expand-icon':'btn-fold-icon'" class=" material-icons">expand_more</span>
          <span>{{ fold ? "展开" : "折叠" }}</span>
        </button>
      </div>
    </div>
    <el-collapse-transition>

      <div class="code-container" v-show="!fold">

        <div ref="codeNode">
          <slot></slot>
        </div>
      </div>
    </el-collapse-transition>


  </div>
</template>

<script>
import {defineComponent, ref} from "vue";
import elCollapseTransition from "./el-collapse-transition.vue";
import {ElPopover} from 'element-plus';


export default defineComponent({
  components: {
    'el-collapse-transition': elCollapseTransition,
    'el-popover': ElPopover,
  },
  name: "blog-code",
  props: {
    language: String,
  },
  setup() {
    let codeNode = ref(null);

    let copied_popover = ref(false);

    function copyNode(node) {
      if ('clipboard' in navigator) {
        return navigator.clipboard.writeText(node.textContent);
      }

      const selection = window.getSelection();

      if (selection == null) {
        return Promise.reject(new Error());
      }

      selection.removeAllRanges();
      const range = document.createRange();
      range.selectNodeContents(node);
      selection.addRange(range);
      document.execCommand('copy');
      selection.removeAllRanges();
      return Promise.resolve();
    }

    let copy = () => {
      let res = copyNode(codeNode.value);
      res.then(() => {
        copied_popover.value = true;
        setTimeout(() => {
          copied_popover.value = false;
        }, 1500)
      })
    };
    return {
      copied_popover,
      fold:ref(false),
      codeNode,
      copy
    }
  }
})
</script>

<style scoped>

</style>